package com.itheima.health.controller;

import com.baomidou.mybatisplus.extension.api.R;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrderSettingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@RestController
@RequestMapping("/ordersetting")
@Slf4j
public class OrderSettingController {
    @Autowired
    private OrderSettingService orderSettingService;

    /**
     * 上传预约设置的excel文件
     *
     * @param file
     * @return
     */
    @RequestMapping("/upload")
    public Result upload(@RequestParam("excelFile") MultipartFile file) {
        log.info("预约设置-上传fileName:{},size:{}", file.getOriginalFilename(), file.getSize());
        String filename = file.getOriginalFilename();
        if (StringUtils.isEmpty(filename)) {
            return new Result(false, "缺少文件名");
        }
        Workbook workbook = null;
        try (InputStream inputStream = file.getInputStream();) {
            if (filename.endsWith(".xls")) {
                //HSSFWorkbook:是操作Excel2003以前(包括2003)的版本,扩展名是.xls
                workbook = new HSSFWorkbook(inputStream);
            } else if (filename.endsWith("xlsx")) {
                //XSSFWorkbook:是操作Excel2007后的版本,扩展名是.xlsx
                workbook = new XSSFWorkbook(inputStream);
            } else {
                return new Result(false, "文件格式不正确，请检查重试");
            }
        } catch (IOException e) {
            log.error("", e);
            return new Result(false, "文件上传失败");
        }
        List<OrderSetting> list = new ArrayList<>();
        for (Sheet sheet : workbook) {
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                //获取行
                Row row = sheet.getRow(i);
                //解析行
                OrderSetting orderSetting = parseOrderSetting(row);
                list.add(orderSetting);
            }
        }
        log.info("预约设置-上传，解析成功，result：{}", list);
        orderSettingService.addAll(list);
        return new Result(true, MessageConst.IMPORT_ORDERSETTING_SUCCESS);
    }

    /**
     * 从excel行提取OrderSetting数据
     *
     * @param row
     * @return
     */
    private OrderSetting parseOrderSetting(Row row) {
        Date date = null;
        Integer number = null;
        //获取日期
        try {
            if (null != row.getCell(0)) {
                //如果单元格没有数据，则getDateCellValue();返回null
                date = row.getCell(0).getDateCellValue();
            }
            //获取最大预约量
            if (null != row.getCell(1)) {
                //如果单元格没有数据，则getNumericCellValue返回0
                double numericCellValue = row.getCell(1).getNumericCellValue();
                //将double型转为int型
                number = Double.valueOf(numericCellValue).intValue();
            }
        } catch (IllegalStateException | NumberFormatException e) {
            log.error("", e);
            throw new BusinessRuntimeException(String.format("数据格式错误,%s 第%d行", row.getSheet().getSheetName(), row.getRowNum() + 1));
        }
        //判断是否缺少数据
        if (null == date || null == number) {
            throw new BusinessRuntimeException(String.format("缺少必填数据,%s 第%d行", row.getSheet().getSheetName(), row.getRowNum() + 1));
        }
        return new OrderSetting(date, number);
    }

    /**
     * 根据月份查询数据
     *
     * @param year
     * @param month
     * @return
     */
    @GetMapping("/getOrderSettingByMonth")
    public Result getOrderSettingByMonth(@RequestParam Integer year, @RequestParam Integer month) {
        List<OrderSetting> orderSettings = orderSettingService.getOrderSettingByMonth(year, month);
        List<Map<String, Object>> list = new ArrayList<>();
        for (OrderSetting orderSetting : orderSettings) {
            // 创建用于日期处理的工具类Calendar对象
            Calendar calendar = Calendar.getInstance();
            //设置时间为预约日期
            calendar.setTime(orderSetting.getOrderDate());
            Map<String, Object> map = new HashMap<>();
            //设置日期限，当月第几天
            map.put("date", calendar.get(Calendar.DAY_OF_MONTH));
            //设置当天允许预约的数量
            map.put("number", orderSetting.getNumber());
            //设置已预约的人数
            map.put("reservations", orderSetting.getReservations());
            list.add(map);
        }
        return new Result(true, MessageConst.GET_ORDERSETTING_SUCCESS, list);
    }

    /**
     *  根据日期编辑
     * @param orderSetting
     * @return
     */
    @RequestMapping("/editNumberByDate")
    public Result editNumberByDate(@RequestBody OrderSetting orderSetting) {
        log.info("根据日期编辑data:{}", orderSetting);
        orderSettingService.editNumberByDate(orderSetting.getOrderDate(), orderSetting.getNumber());
        return new Result(true, MessageConst.ORDERSETTING_SUCCESS);
    }
}
